package com.hz.filemanager.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.hz.filemanager.App;
import com.hz.filemanager.BuildConfig;
import com.hz.filemanager.R;
import com.hz.filemanager.ad.AdLoadManager;
import com.hz.filemanager.ad.utils.AnalyticsUtils;
import com.hz.filemanager.adapter.MainNavigationAdapter;
import com.hz.filemanager.model.DialogManager;
import com.hz.filemanager.model.FileDataManager;
import com.hz.filemanager.ui.base.BaseActivity;
import com.hz.filemanager.ui.base.BaseFragment;
import com.hz.filemanager.ui.base.SelectableFragment;
import com.hz.filemanager.ui.file.MyFileImageListener;
import com.hz.filemanager.ui.file.MyFileTypeListener;
import com.hz.filemanager.ui.fragment.CleanFragment;
import com.hz.filemanager.ui.fragment.FileFragment;
import com.hz.filemanager.ui.fragment.StorageFragment2;
import com.hz.filemanager.utils.PermissionUtil;
import com.hz.sdka.ada.AdListenera;
import com.hz.sdka.ada.Interstitiala;
import com.hz.sdka.commona.bean.HZAdError;
import com.kathline.library.content.ZFileContent;

import java.util.List;

public class MainActivity extends BaseActivity {

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    private BottomNavigationView bottomNav;
    private DrawerLayout drawer;
    private ListView topNavigation;
    private boolean isSelectedModel = false;

    private int indexPage = 0;
    private NavController navController;

    private SelectableFragment currentFragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AnalyticsUtils.INSTANCE.logEvent("jingrusy");

        verifyStoragePermissions(this);
        ZFileContent.getZFileHelp().init(new MyFileImageListener()).setFileTypeListener(new MyFileTypeListener());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEvent() {
        /*bottomNav.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()){
                    case R.id.navigation_clean:
                        AnalyticsUtils.INSTANCE.logEvent("dj_clean");
                        Toast.makeText(MainActivity.this, "clean", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.navigation_file:
                        AnalyticsUtils.INSTANCE.logEvent("dj_file");
                        Toast.makeText(MainActivity.this, "file", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.navigation_storage:
                        AnalyticsUtils.INSTANCE.logEvent("dj_storage");
                        Toast.makeText(MainActivity.this, "store", Toast.LENGTH_SHORT).show();
                        break;
                }

                App.addTabNum();
                int tabClickNumConfig = FileDataManager.appConfig.getFile_Config().getQhcs();
                if(tabClickNumConfig > 0 && App.getTabNum() >= tabClickNumConfig){
                    //弹广告
                    //showAD();
                }
                return false;
            }
        });*/
        bottomNav.setOnItemReselectedListener(new NavigationBarView.OnItemReselectedListener() {
            @Override
            public void onNavigationItemReselected(@NonNull MenuItem item) {
                Toast.makeText(MainActivity.this, "item = " + item.getItemId(), Toast.LENGTH_SHORT).show();
            }
        });

        topNavigation.setAdapter(new MainNavigationAdapter());
        topNavigation.addHeaderView(LayoutInflater.from(this).inflate(R.layout.navigation_header, topNavigation, false));

        navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                switch (destination.getId()) {
                    case R.id.navigation_clean:
                        AnalyticsUtils.INSTANCE.logEvent("dj_clean");
                        toolbar.setNavigationIcon(R.mipmap.nav_left);
                        Toast.makeText(MainActivity.this, "clean", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.navigation_file:
                        AnalyticsUtils.INSTANCE.logEvent("dj_file");
                        toolbar.setNavigationIcon(R.mipmap.nav_left);
                        Toast.makeText(MainActivity.this, "file", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.storageFragment2:
                        AnalyticsUtils.INSTANCE.logEvent("dj_storage");
                        Toast.makeText(MainActivity.this, "store", Toast.LENGTH_SHORT).show();
                        break;
                }

                App.addTabNum();
                int tabClickNumConfig = FileDataManager.appConfig.getFile_Config().getQhcs();
                if (tabClickNumConfig > 0
                        && App.getTabNum() >= tabClickNumConfig
                        && FileDataManager.appConfig.getFile_Config().getTabqh_ad() == 1) {

                    AnalyticsUtils.INSTANCE.logEvent("tabqh_ad");
                    if (Interstitiala.getInstance().isReady()) {
                        AnalyticsUtils.INSTANCE.logEvent("tabqh_ad_ready");
                        //弹广告
                        showAD();
                    }
                }
            }
        });

        topNavigation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://应用图标头区域点击
                        //ignore
                        break;
                    case 1://服务条款
                        Intent service = new Intent(MainActivity.this, ProtocolActivity.class);
                        service.putExtra("type", ProtocolActivity.TERMS_OF_SERVERS);
                        startActivity(service);
                        break;
                    case 2://隐私政策
                        Intent privacy = new Intent(MainActivity.this, ProtocolActivity.class);
                        privacy.putExtra("type", ProtocolActivity.PRIVACY_POLICY);
                        startActivity(privacy);
                        break;
                    case 3://应用市场评分
                        AnalyticsUtils.INSTANCE.logEvent("hp");
                        DialogManager.rateDialog(MainActivity.this);
                        break;
                }
            }
        });
    }

    private void showAD() {
        AdLoadManager.INSTANCE.showInterstitialAd(this, BuildConfig.CJ_SPLASH_AD, new AdListenera() {
            @Override
            public void adError(HZAdError adError) {

            }

            @Override
            public void adClose() {
            }

            @Override
            public void adShow() {
                AnalyticsUtils.INSTANCE.logEvent("tabqh_ad_succeed");
            }
        });
    }

    @Override
    protected void initView() {
        drawer = findViewById(R.id.drawer);
        bottomNav = findViewById(R.id.bottom_navigation);
        topNavigation = (ListView) findViewById(R.id.top_navigation);

        navController = Navigation.findNavController(this, R.id.main_fragment);

        NavigationUI.setupWithNavController(bottomNav, navController);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.file_manager));
        toolbar.setNavigationIcon(R.mipmap.nav_left);
    }

    public void verifyStoragePermissions(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            getPermissionWithR();
        } else {
            PermissionUtil.getInstance().with(this)
                    .requestPermissions(new String[]{
                                    Manifest.permission.READ_EXTERNAL_STORAGE
                                    , Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            new PermissionUtil.PermissionListener() {
                                @Override
                                public void onGranted() {

                                }

                                @Override
                                public void onDenied(List<String> deniedPermission) {
                                    //有权限被拒绝
                                }

                                @Override
                                public void onShouldShowRationale(List<String> deniedPermission) {
                                    //拒绝并不再询问
                                }
                            });
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void getPermissionWithR() {
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + this.getPackageName()));
            startActivityForResult(intent, REQUEST_PERMISSION_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSION_CODE) {

            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    // 如果还是没有获得权限，跳转到当前APP系统设置页面，让用户手动添加权限
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 200) {
            verifyStoragePermissions(this);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (isSelectedModel) {
                    setSelectModelToolbar(false);
                    return true;
                }
                if (drawer.isDrawerOpen(topNavigation)) {
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    drawer.openDrawer(GravityCompat.START);
                }
                return true;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isExit = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isExit = false;
    }

    private boolean isExit = false;

    @Override
    public void onBackPressed() {
        if (TextUtils.isEmpty(StorageFragment2.nowPath) || "root".equals(StorageFragment2.nowPath) || ZFileContent.getSD_ROOT().equals(StorageFragment2.nowPath)) {
            if (currentFragment != null && currentFragment.getModel()){
                setSelectModelToolbar(false);
            }else {
                int id = navController.getCurrentDestination().getId();
                if (id != R.id.navigation_clean) {
                    navController.navigate(R.id.navigation_clean);

                    long lastTime = App.spUtils.getLong("first_exit_time", 0);
                    if (!isExit || (System.currentTimeMillis() - lastTime) > 30 * 1000) {

                        Toast.makeText(MainActivity.this, "Hit exit again", Toast.LENGTH_LONG).show();
                        App.spUtils.putLong("first_exit_time", System.currentTimeMillis());
                        isExit = true;
                    } else {
                        super.onBackPressed();
                    }
                }
            }
        } else {
            isExit = false;
            super.onBackPressed();
        }
    }

    public void setSelectModelToolbar(boolean isSelectModel) {
        currentFragment = (SelectableFragment)getCurrentFragment(StorageFragment2.class);
        assert currentFragment != null;
        Log.e("Test",currentFragment.toString());
        Log.e("Test",currentFragment.getModel()+"");

        if (isSelectModel) {
            toolbar.setNavigationIcon(R.mipmap.cancle);
        } else {
            toolbar.setNavigationIcon(R.mipmap.nav_left);
        }
        currentFragment.updateSelectModelUI(isSelectModel);
        this.isSelectedModel = isSelectModel;
    }

    /**
     * 获取当前NavHostFragment持有的指定的类的实例
     * @param clazz 需要的对应类class
     * @return 实例
     */
    private Fragment getCurrentFragment(Class<? extends BaseFragment> clazz){
        final List<Fragment> allFragment = getSupportFragmentManager().getFragments();
        if (allFragment.size() > 0){
            NavHostFragment navHostFragment = (NavHostFragment) allFragment.get(0);
            final List<Fragment> fragments = navHostFragment.getChildFragmentManager().getFragments();
            if (fragments.size() > 0){
                for (int i = 0; i < fragments.size(); i++) {
                    if (fragments.get(i).getClass().isAssignableFrom(clazz))
                        return fragments.get(i);
                }
            }
        }
        return null;
    }

}